import axios from "axios";

// 一个延时辅助函数，方便查看登录过程
function delay(duration){
	return new Promise((resolve) => {
		setTimeout(()=>{
			resolve();
		},duration)
	})
}

// 用户登录
export async function login(params){
	await delay(500);
	let resp = await axios.post(params.url, params.query);
	if(!resp) return;
	let token = resp.headers.authorization;
	if(token){
		localStorage.setItem("token",token);
	}
	return resp.data.data;
}

// 通过令牌获取登录信息状态
export async function whoAmI(){
	await delay(500);
	let token = localStorage.getItem("token");
	if(!token) return;
	let resp = await axios.get("/api/user/whoami",{
		headers:{
			authorization : `bearer ${token}`
		}
	});
	
	if(!resp) return;
	return resp.data.data;
}

// 注销登录，清除令牌
export function loginOut(){
	localStorage.removeItem("token");
}

// 注册用户
export async function reg(userInfo){
	var resp = await axios.post("/api/user/reg",userInfo);
	return resp.data;
}